#default generic function...
`mapGriddedData` <-function(dataset,fieldToPlot,...){data(gridExampleData,envir=environment(),package="rworldmap");mapGriddedData(get("gridExampleData"),"pa2000.asc",...)}
setGeneric("mapGriddedData")




setMethod("mapGriddedData",c("SpatialGridDataFrame","character"),
function(                dataset = ""
                         ,fieldToPlot=""
                         , numCats = 5  #numCategories in map, later add options for classifying
                         , logIndex = TRUE  #16/3/09 replaced by catMethod below
                         , we=-180, ea=180, so=-90, no=90  #so=-55, no=80 works well to exclude antarctic
                         , numHistBarsPerCat = 1
                         , addTo0ForLog = 0.01
                         , mapRegion = "world"   #sets map extents, overrides we,ea etc.
                         , titleHist=""
                         , addHist=FALSE
                         , addLegend=TRUE
                         , addCountryOutlines=TRUE
                         , plotData=TRUE
                         , catMethod="logFixedWidth"   #any vector defining breaks or "fixedWidth","quantiles","logFixedWidth"
                         , colourPalette= "heat" #"heat","white2Black","topo","palette" for current palette
                         , nameColumnToPlot = "" # only for multi-attribute spatialGridDataframes
                         , countryBorderCol = 'grey'
                         ,aspect=NA
                         ,oceanColour=NA
                         ,countryFillCol=NA
                         #, projection="none" #, "EqualArea"
                         )
   {

    require(maptools)
    require(sp)
    sGDF<-dataset
    attrName<-fieldToPlot
    #require(maps) #i'd like to replace the need for these map outlines



    ## setting map extents if a mapRegion has been specified

    #! trying to see if I can project the grid data
    #seems not to work because the SpatialGridDataFrame gets converted to a SpatialPointsDataFrame
    #gr_wrld_mollweide <- spTransform(gr_wrld, CRS("+proj=moll"))
    #if (projection=="EqualArea")
    #   {
    #    require(rgdal)
    #    sGDF <- spTransform(sGDF, CRS("+proj=moll"))
    #   }


    #if adding histogram open a new window & divide it in two
    if ( addHist )
       {
        oldPar <- par(mfrow=c(2, 1), mai=c(0.5, 0.7, 0.3, 0.3)) # bottom, left, top, right
        on.exit(par(oldPar))
       }


    #CLASSIFYING THE DATA
    sGDF$indexToPlotAsFactor <- rwmApplyClassBreaks( sGDF[[attrName]], catMethod, numCats)
    #because the numColours may be modified slightly from numCats
    numColours <- length(levels(sGDF$indexToPlotAsFactor))
    sGDF$indexToPlot <- as.numeric( sGDF$indexToPlotAsFactor )
    coloursForMap <- rwmGetColours(colourPalette,numColours)




    newMap(mapToPlot=sGDF,oceanColour=oceanColour,projection="none",mapRegion=mapRegion,aspect=aspect)

    if(!is.na(countryFillCol)){
       plotSimpleMap(countryBorderCol=countryFillCol,countryFillCol=countryFillCol)
       }
    #only plot ascii data if plotData=T (allows legend to be plotted on its own by setting plotData=F)
    if (plotData)
        image(sGDF,add=TRUE,attr='indexToPlot',col=coloursForMap, xaxs='i', yaxs='i' ) #xaxs=i ensures maps fill plot area

    if(addCountryOutlines==TRUE){
     plotSimpleMap(countryBorderCol=countryBorderCol)
    }
    
    #add legend to map, can change this to a better legend using the fields package
    #to offer a bunch more options, including whether to use the index val or the actual values
    #legend(x='bottomleft', legend=c(0:numCats), pch = 22, col=c(0:numCats),pt.bg=c(0:numCats), title="index",bg="white" )
    #this one does by map categories
    #legend(x='bottomleft', legend=c(0:numCats), pch = 22, col=c(0,coloursForMap),pt.bg=c(0,coloursForMap), title="index",bg="white" )


	if (addLegend)
    {

      	availablePackages<-.packages(all.available = TRUE)

      	if("spam" %in% availablePackages && "fields" %in% availablePackages){

      	          addMapLegend(sGDF[[attrName]],catMethod=catMethod,colourPalette=colourPalette,numCats=numCats)

      	}else{
      	      #Old style legend if you don't have spam or fields.
          	legend(x='bottomleft', legend=c(rev(levels(sGDF$indexToPlotAsFactor)),"no data"), pch = 15, col=c(coloursForMap[numColours:1],"white"), title="category",bg="white" )
        }
    }











    #could add title
    #!but need to set it to the filename for gridascii files,
    #!and the column name for multi-attribute sGDFs
    #if ( mapTitle == 'columnName' ) title(nameColumnToPlot)
    #else title( mapTitle )



    if ( addHist )
       {
       addHistogram(sGDF$indexToPlot,numCats,titleHist,attrName,numHistBarsPerCat,coloursForMap)
       }

    }
    
  )


setMethod("mapGriddedData",c("character","character"),
function(dataset,fieldToPlot,...){
sGDF<-readAsciiGrid(dataset)
mapGriddedData(sGDF,fieldToPlot,...)
}
)






